package com.youaishujuhui.devops.web.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.gzyouai.hummingbird.common2.util.StringUtil;
import com.youaishujuhui.devops.web.domain.manage.SysUser;
import com.youaishujuhui.devops.web.exception.CustomException;
import com.youaishujuhui.devops.web.exception.ExceptionType;
import com.youaishujuhui.devops.web.service.PropertiesService;
import com.youaishujuhui.devops.web.service.manage.SysUserService;
import com.youaishujuhui.devops.web.util.Common;
import com.youaishujuhui.devops.web.util.SignTool;
import com.youaishujuhui.devops.web.util.WebUtil;

/**
 * 用户登录登出
 **/
@Controller
@RequestMapping("/")
public class LoginController {

	private Logger log = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private PropertiesService propertiesService;
	
	@Autowired
	private SysUserService sysUserService;

	@RequestMapping("/passportLogin")
	public ModelAndView passportLogin(HttpServletRequest request, String appId, String time, String rndText,
			String staffCode, String name, String namePhonetic, String sign) throws Exception {

		String backUrl = request.getParameter("backUrl");
		String requersProductId = request.getParameter("productId");
		
		Map<String, String> signParam = new HashMap<>();
		signParam.put("appId", appId);
		signParam.put("time", time);
		signParam.put("staffCode", staffCode);
		signParam.put("rndText", rndText);
		signParam.put("name", name);
		signParam.put("namePhonetic", namePhonetic);

		String localSign = SignTool.sign(signParam, propertiesService.getPassportLoginKey());

		if (!localSign.equals(sign) || !appId.equals(propertiesService.getPassportAppId())) {
			throw new CustomException(ExceptionType.AUTH_FAIL);
		}

		SysUser user = sysUserService.getByUserName(staffCode);
		if (user == null) {
			System.out.println("用户尚不存在");
			user = sysUserService.insert(staffCode);
			System.out.println("插入新用户，用户id为：" + user.getUId());
		} else {
			System.out.println("用户已存在，用户id是：" + user.getUId());
		}
		
		// 缓存该用户拥有的资源
		user.setResourceUris(sysUserService.getResources(staffCode));

		// 存入session
		WebUtil.setLoginUser(request, user);
		
		ModelAndView modelAndView = new ModelAndView();
		log.info("backUrl>>>>>>>" + backUrl);
		
		// 跳转
		if(!StringUtil.isNullOrEmpty(backUrl) && !"undefined".equals(backUrl)
				&& !"null".equals(backUrl)){
			modelAndView.setViewName("redirect:" + backUrl);
			return modelAndView;
		} else {
			modelAndView.setViewName("redirect:/");
		}

		return modelAndView;		

//        LoginUserPO loginUser = loginService.findByUserName(param);
//
//        if(loginUser == null){
//            throw new CustomException(ExceptionType.AUTH_FAIL);
//        }else{
//            loginUser.setName(URLDecoder.decode(name,"UTF-8"));
//            if(propertiesService.getPermissionEnable()){
//
//                Map<String,String> requestParam = new HashMap<>();
//                requestParam.put("username",staffCode);
//                requestParam.put("appId",propertiesService.getPermissionAppId());
//                String permissionSign = SignTool.sign(requestParam,propertiesService.getPermissionSecretKey());
//                requestParam.put("sign",permissionSign);
//                CloseableHttpClient httpClient = HttpClientUtils.getHttpClient();
//                String permissionResult = HttpClientUtils.doPost(httpClient,propertiesService.getPermissionUrl(),requestParam);
//                HttpClientUtils.closeHttpClient(httpClient);
//                AppPermissionResult appPermissionResult = JSON.parseObject(permissionResult,AppPermissionResult.class);
//                if(appPermissionResult.getCode()!=Result.SUCCESS){
//                    throw new CustomException(ExceptionType.AUTH_FAIL);
//                }
//                List<Product> products = appPermissionResult.getProducts();
//                if(products == null || products.size()==0){
//                    throw new CustomException(ExceptionType.AUTH_FAIL);
//                }
//                Set<String> roleCodes = new HashSet<>();
//                for(Product product : products){
//                    List<Role> roles = product.getRoles();
//                    if(roles!=null){
//                        for(Role role : roles){
//                            roleCodes.add(role.getRoleCode());
//                        }
//                    }
//                }
//                Map<String,Set<String>> roleUriMap = loginService.findProductResourceByRoleCodes(String.format("'%s'",StringUtils.join(roleCodes,"','")));
//
//                Map<String,Integer> productMap = new HashMap<>();
//                List<SysProductPO> productPOList =  productService.loadAll();
//                for (SysProductPO productPO : productPOList){
//                    productMap.put(productPO.getCode(),productPO.getId());
//                }
//
//                Map<String,Set<String>> productUriMap = new HashMap<>();
//                Set<String> resourceUris = new HashSet<>();
//                Set<Integer> productIds = new HashSet<>();
//                for(Product product : products){
//                    Integer productId = productMap.get(product.getProductCode());
//                    productIds.add(productId);
//                    Set<String> uriSet = productUriMap.get(productId.toString());
//                    if(uriSet==null){
//                        uriSet = new HashSet<>();
//                    }
//                    List<Role> roles = product.getRoles();
//                    if(roles!=null){
//                        for(Role role : roles){
//                            uriSet.addAll(roleUriMap.get(role.getRoleCode()));
//                            resourceUris.addAll(roleUriMap.get(role.getRoleCode()));
//                        }
//                    }
//                    productUriMap.put(productId.toString(),uriSet);
//                }
//                loginUser.setProductIds(productIds);
//                loginUser.setProductIdUriMap(productUriMap);
//                loginUser.setResourceUris(resourceUris);
//
//            }else{
//                Map<String,Set<String>> productUriMap = loginService.getProductUriMap(loginUser.getId());
//                loginUser.setResourceUris(productUriMap.get("all"));
//                productUriMap.remove("all");
//                loginUser.setProductIdUriMap(productUriMap);
//            }
//            /*Map<Integer,Set<Integer>> productChannelMap = loginService.getProductChannelMap(loginUser.getId());
//            loginUser.setProductChannelMap(productChannelMap);*/
//            loginService.setChannelServerLimit(loginUser);
//
//            WebUtil.setLoginUser(request, loginUser);
//        }
//
//
//        ModelAndView modelAndView = new ModelAndView();
//        log.info("backUrl>>>>>>>"+backUrl);
//        if(!StringUtil.isNullOrEmpty(backUrl)&&!"undefined".equals(backUrl)&&!"null".equals(backUrl)){
//            modelAndView.setViewName("redirect:"+backUrl);
//            return modelAndView;
//        }else{
//            modelAndView .setViewName("redirect:/");
//        }
//
//        return modelAndView;

	}
	
    @RequestMapping("/logout")
    public ModelAndView logout(HttpServletRequest request) {
        WebUtil.removeLoginUser(request);
        ModelAndView modelAndView = new ModelAndView("redirect:"+propertiesService.getPassportLogoutUrl());
        return modelAndView;
    }

}
